<template>
  <div class="workbench1">

    <div v-show="isListShow">
      <header>
        <div class="search searchMini">
          <div class="homeSearch icoo"></div>
          <input type="text" v-model="searchValue" class="homeInput" placeholder="输入关键字" @keyup.enter="searchKeyUp()" maxlength="20" />
          <img draggable="false" src="static/image/home/clear_icon.png" class="s_clear_icon" @click="clearSearchValue()" v-show="searchValue.trim() != ''" />
        </div>
        <div class="search searchPerson">
          <div class="perSearch icoo"></div>
          <input type="text" v-model="searchValuePerson" class="homeInput" placeholder="搜索会话对象" @keyup.enter="searchKeyUp()" />
          <img draggable="false" src="static/image/home/clear_icon.png" class="s_clear_icon" @click="clearSearchValuePerson()" v-show="searchValuePerson.trim() != ''" />
        </div>
        <div class="search">
          <el-date-picker v-model="msgTime" type="datetimerange" align="right" unlink-panels format="yyyy.MM.dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss" range-separator="-" start-placeholder="开始日期"
            end-placeholder="结束日期" :picker-options="$store.state.pickerOptions">
          </el-date-picker>
        </div>
      </header>
      <div class="list1">
        <div class="title">
          <span>会话对象</span>
          <span>最后联系时间</span>
          <span>相关信息条数</span>
        </div>
        <ul>
          <li v-for="(temp, index) in search_list_array.msg" :key="index + '_key'" :class="[temp1 == temp ? 'select_act' : 'listInfoBg']" class="listInfo" @click="fun1(temp)">
            <span>{{ temp.name }}</span>
            <span>{{ temp.time | getTimeAll }}</span>
            <span>{{ temp.count }}</span>
          </li>
        </ul>
      </div>
      <section class="blank"></section>
      <div class="list2">
        <div class="detailItem">
          <div class="item" v-for="(item, index) in detailArrayS" :key="`item_${index}`" :class="{ itemChoose: recordId == item.messageId }" @click="showRecords(true, item)">
            <div class="itemcontent" v-if="item.type == 'file'">
              <span style="width: 16px">{{ index + 1 }}</span>
              <img class="file_pic" draggable="false" v-lazy="$utilJs.getFileType(item.value)" style="width: 14px; height: 14px; margin: 0 3px 0 0" />
              <span class="value" v-html="
                  $replaceKeyWords(item.value, oldsearchval, '#fa7500', 30)
                "></span>
            </div>
            <div class="itemcontent" v-else>
              <span style="width: 16px">{{ index + 1 }}</span>
              <span class="value" v-html="
                  $replaceKeyWords(
                    item.value.replace(/&nbsp;/g, ''),
                    oldsearchval,
                    '#fa7500',
                    26
                  )
                "></span>
            </div>
            <div class="time">
              <img v-if="item.name == myInfo.name" src="static\image\home\label_sender_my.png" style="width: 28px; height: 16px" />
              <span class="name" v-else>{{ item.name }}</span>
              | {{ item.time | getTimeAll }}
            </div>
          </div>
        </div>
        <div class="foot" v-show="total > 1">
          <div class="btn_d">
            <img src="static\image\home\page_last_s.png" style="width: 16px; height: 16px" :class="{ 'foot-op': this.nowPage == 1 }" @click="nextPage" />
            <img src="static\image\home\page_next_s.png" style="width: 16px; height: 16px" :class="{ 'foot-op': this.nowPage >= this.total }" @click="lastPage" />
          </div>
          <span style="color: #e6e6e6; margin: 0 8px 5px 8px">|</span>
          <span style="margin: 0 0px 3px 3px">当前第 {{ nowPage }} 页 共 {{ total }} 页</span>
        </div>
      </div>
    </div>
    <message-detail v-show="!isListShow" :detailArray="detailArrayS" :recordId="recordId" :recordList="recordList" :isListShow="isListShow" :staticArray="staticArray" :searchArray="searchArray" :toName="toName"
      :toInfo="toInfo" :playerOptions="playerOptions" @back="isListShow = true" @showRecords="showRecords" @searchMdbTochat="searchMdbTochat" @toForwarding="toForwarding" @toDownFile="toDownFile" @toBacklog="toBacklog">
    </message-detail>
  </div>
</template>

<script>
import messageDetail from "./message-detail.vue"; //组织架构列表组件
export default {
  name: "structureMain",
  props: {
    searchQuery: {
      default: "",
    },
    comprehensive: "",
    setHistoryMsg: {
      type: Function,
    },
    toInfo: {
      type: Object,
      default: {
        id: "",
        name: "",
        isGroup: false,
      },
    },
    playerOptions: {
      type: Object,
      default: {},
    },
    isSearchShow: {
      type: Boolean,
    },
  },
  components: {
    messageDetail,
  },
  data() {
    return {
      oldsearchval: "",
      searchValue: "",
      recordList: null,
      groupListShow: null,
      isListShow: true,
      rightShow: false,
      searchValuePerson: "",
      detailArray: [],
      defaultImg: 'this.src="static/image/home/person_1.png"',
      recordId: "",
      staticArray: null,
      searchArray: null,
      toName: "",
      msgTime: null,
      startTimeS: "",
      endTimeS: "",
      nowPage: 1,
      total: 0,
      size: 10,
      detailArrayS: [],
      temp1: {},
      oldsearchValuePerson: "",
      oldsearchValue: "",
      timer: "", //change延迟事件时间
    };
  },
  computed: {
    myInfo() {
      return this.$store.state.myInfo;
    },
    search_list_array: {
      get() {
        return this.$store.state.search_list_array;
      },
      set(val) {
        this.$store.commit("setsearchListArr", val);
      },
    },
    // searchValue: {
    //   get() {
    //     this.detailArrayS = [];
    //     // return this.$store.state.searchValue;
    //     return this.comprehensive;
    //   },
    //   set(val) {
    //     // this.$store.commit("setsearchValueH", val);
    //     this.comprehensive = val;
    //   },
    // },
    // oldsearchval: {
    //   get() {
    //     return this.$store.state.oldsearchval;
    //   },
    //   set(val) {
    //     this.$store.commit("setoldsearchval", val);
    //   },
    // },
    sqlTable() {
      return {
        userInformation: `user_information_${this.myInfo.id}`, //用户信息表
        messageList: `message_list_${this.myInfo.id}`, //群聊消息表
        privateList: `private_list_${this.myInfo.id}`, //单聊消息表
        sessionList: `session_list_${this.myInfo.id}`, //会话列表
        groupList: `group_list_${this.myInfo.id}`, //群列表
      };
    },
  },
  watch: {
    msgTime() {
      this.searchKeyUp();
    },
    searchValuePerson(newVal, oldVal) {
      this.changeValueSearch(newVal, oldVal);
    },
    searchValue(newVal, oldVal) {
      this.changeValueSearch(newVal, oldVal);
    },
    isSearchShow() {
      this.isListShow = true;
    },

    comprehensive(val) {
      this.searchValue = val;
    },
    searchQuery(val) {
      this.searchValue = val;
    },
  },
  methods: {
    toBacklog(item) {
      this.$emit("toBacklog", item);
    },
    clearSearchValuePerson() {
      this.searchValuePerson = "";
      this.searchKeyUp();
    },
    clearSearchValue() {
      this.searchValue = "";
      this.searchKeyUp();
    },
    nextPage() {
      //上一页
      if (this.nowPage <= 1) {
        return false;
      } else {
        this.nowPage--;
        this.paginationList();
      }
    },
    lastPage() {
      //下一页
      if (this.nowPage >= this.total) {
        return false;
      } else {
        this.nowPage++;
        this.paginationList();
      }
    },
    paginationList() {
      let i = this.temp1.id;
      let sVal = this.getSearchVal(i);
      //数组分页
      let index1 = (this.nowPage - 1) * this.size;
      if (this.temp1.isGroup == 0) {
        // zk127修改，按时间降序排列
        var msga_list = this.$operationalDatabase(
          `SELECT a.*,b.*,0 isGroup FROM ${this.sqlTable.privateList} a,${this.sqlTable.userInformation} b WHERE a.value LIKE '%${this.oldsearchValue}%' ${sVal.searchId} ${sVal.searchSender} ${sVal.startTimeS} ${sVal.endTimeS} AND (a.type == 'text' OR a.type == 'file') AND a.sendId=b.id GROUP BY messageId ORDER BY time DESC LIMIT ${index1},${this.size}`,
          1
        );
        console.log(
          `SELECT a.*,b.*, 0 isGroup FROM ${this.sqlTable.privateList} a,${this.sqlTable.userInformation} b WHERE a.value LIKE '%${this.oldsearchValue}%' ${sVal.searchId} ${sVal.searchSender} ${sVal.startTimeS} ${sVal.endTimeS} AND (a.type == 'text' OR a.type == 'file') AND a.sendId=b.id GROUP BY messageId ORDER BY time DESC LIMIT ${index1},${this.size}`
        );
        this.detailArrayS = msga_list.list;
      } else {
        var msgb_list = this.$operationalDatabase(
          `SELECT a.*,b.* ,1 isGroup FROM ${this.sqlTable.messageList} a,${this.sqlTable.groupList} b WHERE a.value LIKE '%${this.oldsearchValue}%' ${sVal.searchIdb} ${sVal.searchSender} ${sVal.startTimeS} ${sVal.endTimeS} AND (a.type == 'text' OR a.type == 'file') AND a.receiveId=b.id ORDER BY time DESC LIMIT ${index1},${this.size};`,
          1
        );
        this.detailArrayS = msgb_list.list;
      }
    },
    fun1(temp) {
      this.staticArray = { ...temp };
      this.searchArray = { ...temp };
      this.detailArray = temp.data;
      this.temp1 = temp;
      this.toName = temp.name;
      this.nowPage = 1;
      this.total = Math.ceil(temp.count / this.size);
      this.paginationList();
    },
    fn2(temp) {
      this.recordId = temp.messageId;
      this.isListShow = false;
    },
    getSearchVal(i) {
      var ct1 = "",
        ct2 = "",
        startTimeS = "",
        endTimeS = "",
        searchSender = "",
        searchId = "",
        searchIdb = "";
      ct2 = new Date().getTime();
      if (!this.oldsearchval && !this.msgTime && !this.searchValuePerson) {
        ct1 = ct2 - 86400000;
      }
      if (this.msgTime) {
        ct1 = new Date(this.msgTime[0]).getTime();
        ct2 = new Date(this.msgTime[1]).getTime();
      }
      if (this.msgTime) {
        ct1 = new Date(this.msgTime[0]).getTime();
        ct2 = new Date(this.msgTime[1]).getTime();
      }
      startTimeS = ct1 ? `AND a.time >= '${ct1}'` : "";
      endTimeS = ct2 ? `AND a.time <= '${ct2}'` : "";
      searchSender = this.oldsearchValuePerson
        ? `AND a.name LIKE '%${this.oldsearchValuePerson}%'`
        : "";
      searchId = `AND (a.receiveId = '${i}' OR a.sendId = '${i}')`;
      searchIdb = `AND a.receiveId = '${i}'`;
      return {
        ct1,
        ct2,
        startTimeS,
        endTimeS,
        searchSender,
        searchId,
        searchIdb,
      };
    },
    searchMdbTochat(e) {
      this.$emit("searchMdbTochat", e);
    },
    toForwarding(e) {
      this.$emit("toForwarding", e);
    },
    toDownFile(e) {
      this.$emit("toDownFile", e);
    },
    searchKeyUp() {
      let info = this.searchValue.replace(/\s+/g, ""); // 去除空格
      this.oldsearchval = info; //zk125新增，保存上次搜索内容，便于展示
      this.pageSize = 10; // 初始化分页
      this.pageNumRecord = 1; // 初始化分页 聊天记录
      let ct1 = "";
      let ct2 = new Date().getTime();
      if (!this.oldsearchval && !this.msgTime && !this.searchValuePerson) {
        ct1 = ct2 - 86400000;
      }
      if (this.msgTime) {
        ct1 = new Date(this.msgTime[0]).getTime();
        ct2 = new Date(this.msgTime[1]).getTime();
      }
      this.startTimeS = ct1 ? `AND time >= '${ct1}'` : "";
      this.endTimeS = ct2 ? `AND time <= '${ct2}'` : "";
      this.oldsearchValuePerson = this.searchValuePerson;
      this.oldsearchValue = this.searchValue;

      let msg_list = this.get_chat_records();
      this.search_list_array.msg = msg_list;
    },
    // 查询记录,zk118标注，搜索时，聊天记录查找本地数据库
    get_chat_records() {
      this.detailArrayS = [];
      let ct1 = "";
      let ct2 = new Date().getTime();
      if (!this.oldsearchval && !this.msgTime && !this.searchValuePerson) {
        ct1 = ct2 - 86400000;
      }
      if (this.msgTime) {
        ct1 = new Date(this.msgTime[0]).getTime();
        ct2 = new Date(this.msgTime[1]).getTime();
      }
      let startTimeS = ct1 ? `AND pl.time >= '${ct1}'` : "";
      let endTimeS = ct2 ? `AND pl.time <= '${ct2}'` : "";
      let searchSender = this.oldsearchValuePerson
        ? `AND pl.name LIKE '%${this.oldsearchValuePerson}%'`
        : "";
      let startTimeS1 = ct1 ? `AND ml.time >= '${ct1}'` : "";
      let endTimeS1 = ct2 ? `AND ml.time <= '${ct2}'` : "";
      let searchSender1 = this.oldsearchValuePerson
        ? `AND ml.name LIKE '%${this.oldsearchValuePerson}%'`
        : "";

      let private_info = this.$operationalDatabase(
        `select * from( select id id,name name,time,count(*) count,0 isGroup  from(SELECT ui.*,pl.time FROM
            ${this.sqlTable.privateList} pl
          INNER JOIN ${this.sqlTable.userInformation} ui ON (
            ui.id = pl.receiveId
            AND pl.sendId = '${this.myInfo.id}'
          )
          OR (
            ui.id = pl.sendId
            AND pl.sendId <> ${this.myInfo.id}
          )
          WHERE
            pl.value LIKE '%${this.oldsearchval}%' ${startTimeS}${endTimeS}${searchSender}
            AND (pl.type == 'text' OR pl.type == 'file')
          ) GROUP BY
            id,
            name

          union all

          select id id,name name,time,count(*) count, 1 isGroup from(

          SELECT
            ml.receiveId id,gl.name name,ml.time time
          FROM
            ${this.sqlTable.messageList} ml
          LEFT JOIN ${this.sqlTable.groupList} gl ON (
            gl.id = ml.receiveId
          )
          WHERE
            ml.value LIKE '%${this.oldsearchval}%' ${startTimeS1}${endTimeS1}${searchSender1}
            AND (ml.type == 'text' OR ml.type == 'file')
          ) GROUP BY
            id,
            name) ORDER BY time desc`,
        1
      );

      return Object.values(private_info.list);
    },
    showRecords(flag, info) {
      //zk120
      if (flag) {
        //打开时同时获取数据
        this.recordList = [];
        this.recordId = info.messageId;
        console.log(info, "点击的那条历史记录的详情");
        // let id = info.id;
        let id;
        id = info.isGroup == 1 ? info.id : this.staticArray.id;
        let isTrue = info.isGroup == "1";
        var str;
        str = `${
          isTrue ? this.sqlTable.messageList : this.sqlTable.privateList
        } a left join ${
          this.sqlTable.userInformation
        } b on a.sendId=b.id WHERE (${
          isTrue
            ? "a.receiveId='" + id + "'"
            : "a.sendId='" + id + "' OR a.receiveId='" + id + "'"
        })`;
        console.log(str);
        let res = this.$operationalDatabase(
          `SELECT a.*,b.head FROM  ${str} ORDER BY time DESC;`,
          1
        );
        let len = res.list.length;
        for (let i = 0, len = res.list.length; i < len; i++) {
          res.list[i].value = this.setHistoryMsg(res.list[i]);
        }
        this.recordList = res.list;
        console.log(this.recordList, "点击的那条历史记录");
        this.isListShow = false;
      }
    },
    changeValueSearch(val, oldVal) {
      console.log(val, oldVal, 534);
      //监听input框的值改变
      clearTimeout(this.timer); //先清除之前的定时器
      this.timer = setTimeout(() => {
        if (oldVal !== val) {
          this.searchKeyUp();
        }
      }, 500);
    },
  },
  created() {
    // 2022/4/18 zc 新增切换导航栏清空聊天记录搜索对象和时间
    this.$bus.$on("clearSearch", () => {
      this.searchValuePerson = "";
      this.msgTime = null;
    });
  },
  mounted() {
    this.searchKeyUp();
  },
};
</script>
<style lang="less" scoped>
.workbench1 {
  height: calc(100% - 40px);
}
header {
  display: flex;
  margin: 8px 10px;
}
.search {
  text-align: left;
  background-color: #f7f7f7;
  border-radius: 4px;
  display: flex;
  align-items: center;
  margin: 0 4px;
  input {
    font-size: 12px;
  }
  .icoo {
    background-size: 50%;
  }
  .homeInput {
    background-color: #f7f7f7;
    width: 70%;
  }
  .s_clear_icon {
    margin-right: 10px;
    cursor: pointer;
  }
  /deep/.el-input__inner {
    background-color: #f7f7f7;
    border: none;
    height: 30px;
    padding: 0 10px;
    .el-range-input {
      background-color: #f7f7f7;
      line-height: 30px;
      width: 56%;
      font-size: 12px;
    }
  }
  /deep/.el-date-editor {
    width: 180px !important;
  }
  /deep/.my_el_select {
    width: 120px;
  }
  /deep/.el-range-separator {
    padding: 0;
    width: 10px;
  }
}
.list1 {
  margin: 0 12px 0 14px;
  height: 200px;
  line-height: 32px;
  span {
    width: 25%;
  }
  .title {
    background-color: #f5f5f5;
    border-top: 1px solid #e5e5e5;
    border-bottom: 1px solid #e5e5e5;
    display: flex;
    justify-content: space-between;
  }
  ul {
    height: 162px;
    overflow-y: scroll;
    .listInfo {
      display: flex;
      justify-content: space-between;
    }
    .listInfoBg {
      border-bottom: 1px solid #e5e5e5;
    }
    .listInfoBg:nth-child(even) {
      background-color: #f5f5f5;
    }
  }
}
.select_act {
  background-color: #fff4eb;
  border-top: #ffbb7f solid 1px;
  border-bottom: #ffbb7f solid 1px;
}
.detailItem {
  height: calc(100vh - 320px);
  width: 100%;
  overflow-y: scroll;
  .item {
    cursor: pointer;
    display: flex;
    justify-content: space-between;
    padding: 6px 20px;
    overflow: hidden;
    img {
      margin: 0 6px;
    }
    .itemcontent {
      flex: 1;
      text-align: left;
      margin: 0 30px 0 10px;
      font-size: 14px;
      span {
        color: #999;
        margin-right: 10px;
      }
      .name {
        font-size: 16px;
        color: #333;
        // font-weight: bold;
        line-height: 20px;
      }
      .value {
        color: #666;
        line-height: 22px;
        font-size: 14px;
        word-break: break-all;
      }
    }
    .time {
      color: #999;
      img {
        top: 4px;
        position: relative;
      }
    }
  }
  .itemChoose {
    background-color: #fff4eb;
    border-bottom: #ffbb7f solid 1px;
    border-top: #ffbb7f solid 1px;
  }
}
.blank {
  height: 6px;
  background-color: #eeeeee;
}
.foot {
  display: flex;
  height: 30px;
  background: white;
  border-top: 1px solid #e5e5e5;
  align-items: center;
  width: 100%;
  position: fixed;
  padding-left: 20px;
}
.foot-op {
  opacity: 0.5;
}
</style>
